package xyz.lisys.boot.service;

import lombok.val;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.text.MessageFormat;

@Service
public class EntryService {

    @Resource
    public RestTemplate restTemplate;

    @Resource
    public DiscoveryClient discoveryClient;

    @Resource
    public LoadBalancerClient loadBalancerClient;

    public String getEntry() {
        val services = discoveryClient.getServices();
        if (CollectionUtils.isEmpty(services)) {
            return null;
        }

        val instances = discoveryClient.getInstances("entry");
        if (CollectionUtils.isEmpty(instances)) {
            return null;
        }

        val serviceInstance = instances.get(0);
        val url = MessageFormat.format(
                "http://{0}:{1}/index",
                serviceInstance.getHost(), String.valueOf(serviceInstance.getPort())
        );

        val response = restTemplate.exchange(
                url, HttpMethod.GET, null,
                new ParameterizedTypeReference<String>() {
                }
        );

        return response.getBody();
    }

    public String getEntryByLoadBalancerClient() {
        // Ribbon负载均衡器
        val serviceInstance = loadBalancerClient.choose("entry");
        if (serviceInstance == null) {
            return null;
        }

        val url = MessageFormat.format(
                "http://{0}:{1}/index",
                serviceInstance.getHost(), String.valueOf(serviceInstance.getPort())
        );

        val response = restTemplate.exchange(
                url, HttpMethod.GET, null,
                new ParameterizedTypeReference<String>() {
                }
        );

        return response.getBody();
    }

    public String getEntryByLoadBalancerAnnotation() {
        // 为RestTemplate增加LoadBalanced注解
        val response = restTemplate.exchange(
                "http://entry/index", HttpMethod.GET, null,
                new ParameterizedTypeReference<String>() {
                }
        );

        return response.getBody();
    }
}
